"use client";

import React, { createContext, useContext, ReactNode, useState, useEffect } from 'react';
import { apiClient } from '@/lib/api-client';
import { ChatMessage, ChatCompletionRequest } from '@/lib/types';
import { v4 as uuidv4 } from 'uuid';

interface ApiContextType {
  messages: ChatMessage[];
  isLoading: boolean;
  isConnected: boolean;
  error: string | null;
  sendMessage: (content: string, userId?: string, conversationId?: string) => Promise<void>;
  sendMessageStream: (content: string, userId?: string, conversationId?: string) => Promise<void>;
  clearMessages: () => void;
  checkConnection: () => Promise<boolean>;
  loadThreadMessages: (threadId: string) => Promise<void>;
  setMessages: (messages: ChatMessage[]) => void;
}

const ApiContext = createContext<ApiContextType | undefined>(undefined);

export function ApiProvider({ children }: { children: ReactNode }) {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isConnected, setIsConnected] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 检查连接状态
  const checkConnection = async (): Promise<boolean> => {
    try {
      const healthResponse = await apiClient.healthCheck();
      const isHealthy = healthResponse.status === 'healthy';
      setIsConnected(isHealthy);
      if (isHealthy) {
        setError(null);
      }
      return isHealthy;
    } catch (err) {
      setIsConnected(false);
      setError(err instanceof Error ? err.message : 'Connection failed');
      return false;
    }
  };

  // 发送普通消息
  const sendMessage = async (content: string, userId?: string, conversationId?: string) => {
    if (isLoading) return;
    
    setIsLoading(true);
    setError(null);
    
    const userMessage: ChatMessage = { role: 'user', content, id: uuidv4(), type: 'human' };
    setMessages(prev => [...prev, userMessage]);

    try {
      const request: ChatCompletionRequest = {
        messages: [...messages, userMessage],
        userId,
        conversationId,
        stream: false
      };

      const response = await apiClient.chatCompletions(request);
      
      if (response.choices && response.choices.length > 0) {
        const assistantMessage = response.choices[0].message;
        setMessages(prev => [...prev, assistantMessage]);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to send message');
      // 移除用户消息如果发送失败
      setMessages(prev => prev.slice(0, -1));
    } finally {
      setIsLoading(false);
    }
  };

  // 发送流式消息
  const sendMessageStream = async (content: string, userId?: string, conversationId?: string) => {
    if (isLoading) return;
    
    setIsLoading(true);
    setError(null);
    
    const userMessage: ChatMessage = { role: 'user', content, id: uuidv4(), type: 'human' };
    setMessages(prev => [...prev, userMessage]);

    try {
      const request: ChatCompletionRequest = {
        messages: [...messages, userMessage],
        userId,
        conversationId,
        stream: true
      };

      let assistantContent = '';
      const assistantMessage: ChatMessage = { role: 'assistant', content: '', id: uuidv4(), type: 'ai' };
      
      // 添加空的助手消息
      setMessages(prev => [...prev, assistantMessage]);

      // 处理流式响应
      for await (const chunk of apiClient.chatCompletionsStream(request)) {
        assistantContent += chunk;
        setMessages(prev => {
          const newMessages = [...prev];
          newMessages[newMessages.length - 1] = {
            ...assistantMessage,
            content: assistantContent,
            id: assistantMessage.id
          };
          return newMessages;
        });
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to send stream message');
      // 移除用户消息和空的助手消息如果发送失败
      setMessages(prev => prev.slice(0, -2));
    } finally {
      setIsLoading(false);
    }
  };

  const clearMessages = () => {
    setMessages([]);
    setError(null);
  };

  // 从threads数据中加载历史消息
  const loadThreadMessages = async (threadId: string) => {
    if (!threadId) {
      clearMessages();
      return;
    }
    
    setIsLoading(true);
    setError(null);
    
    try {
      // 这里需要从ThreadProvider获取threads数据
      // 由于架构限制，我们需要通过props或context传递threads数据
      // 暂时先清空消息，后续在Thread组件中直接处理
      clearMessages();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load thread messages');
    } finally {
      setIsLoading(false);
    }
  };

  // 直接设置消息的方法
  const setMessagesDirectly = (newMessages: ChatMessage[]) => {
    setMessages(newMessages);
  };

  // 初始化时检查连接
  useEffect(() => {
    checkConnection();
  }, []);

  const value: ApiContextType = {
    messages,
    isLoading,
    isConnected,
    error,
    sendMessage,
    sendMessageStream,
    clearMessages,
    checkConnection,
    loadThreadMessages,
    setMessages: setMessagesDirectly,
  };

  return (
    <ApiContext.Provider value={value}>
      {children}
    </ApiContext.Provider>
  );
}

export function useApi(): ApiContextType {
  const context = useContext(ApiContext);
  if (context === undefined) {
    throw new Error('useApi must be used within an ApiProvider');
  }
  return context;
}